<template>
    <div class="alarm-stat flex column" style=" height: 100%;overflow-x: hidden">
      <!--      搜索区-->
      <collapse ref="collapse">
        <template v-slot:content>
          <yz-condition-filter
              v-model="params"
              @resetSearch="resetSearch"
              @onSubmit="onSubmit"
              style="margin-top: 4px;"
          >
            <yz-input
                v-model.trim="params.dateRange"
                class="q-mr-md"
                inputType="date"
                hint="选择时间范围"
                isTip
                title="日期"
            ></yz-input>
            <workshop-search v-model="params" ref="workShopSearch" :is-shift="false"/>
          </yz-condition-filter>
          <div class="form-inline bottom justify-between items-center">
            <q-btn class="btn margin-r-10"
                   outline
                   color="primary"
                   :disable="!tableData.length"
                   @click="exportExcel">
              导出Excel
            </q-btn>
            <div class="text-grey font-size-14">*柏拉图：{{statusList[4].label}}时长/班制时长</div>
          </div>
        </template>
      </collapse>
      <div style="flex: 1;padding: 0;margin-bottom: 20px" class="scroll-y scrollbar">
        <div class="relative-position">
          <div class="full-width text-center" style="font-size: 16px;font-weight: 500">{{statusList[4].label}}总次数：{{this.pagination.rowsNumber}}</div>
        </div>
        <q-table :data="tableData"
                 :columns="tableColumns"
                 row-key="alarmNum"
                 :pagination.sync="pagination"
                 :hide-bottom="!!tableData.length"
                 class="myTable scroll stick-last-col"
                 color="primary">
          <template v-slot:header-cell-time="props">
            <q-th :props="props"
                  class="sortable"
                  :class="[params.sortBy == 'time' ? 'sorted' : '','sort-' +params.value]"
                  @click="sortable('time')">
              {{ props.col.label }}
              <q-icon name="arrow_upward"
                      size="16px"
                      class="q-table__sort-icon" />
            </q-th>
          </template>
        </q-table>
        <yz-pagination v-model="pagination" @onSearch="getList"/>
      </div>
    </div>
</template>

<script>
import Collapse from 'src/components/collapse'
import { date } from 'quasar'
import { getAlarmList, downloadAlarm, getAlarmChartData } from 'src/boot/statistics/alarm-stat'
import moment from 'moment'
import { mapGetters } from 'vuex'
import _ from 'lodash'
export default {
  name: 'alarm-stat',
  components: {
    Collapse
  },
  computed: {
    ...mapGetters([
      'client', 'statusList'
    ]),
    tableColumns () {
      return [
        { name: 'time', field: 'time', label: `${this.statusList[4].label}时间`, align: 'left' },
        { name: 'deviceNameAndNo', field: 'deviceNameAndNo', label: '设备名称(编码）', align: 'left' },
        { name: 'location', field: 'location', label: '所在位置', align: 'left' },
        { name: 'alarmNo', field: 'alarmNo', label: `${this.statusList[4].label}编号`, align: 'left' },
        { name: 'alarmType', field: 'alarmType', label: `${this.statusList[4].label}类型`, align: 'left' },
        { name: 'alarmContent', field: 'alarmContent', label: `${this.statusList[4].label}原因`, align: 'left' },
        { name: 'durationStr', field: 'durationStr', label: `${this.statusList[4].label}时长`, align: 'left' }
      ]
    }
  },
  data () {
    return {
      requestId: null, // 导出唯一标识
      params: {
        dateRange: [date.subtractFromDate(new Date(), { days: 6 }), new Date()],
        sortBy: 'alarmTime',
        value: 'desc',
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        },
        devices: ['all']
      },
      statusOptions: [
        {
          label: '全部',
          value: null,
          color: null
        }
      ],
      chartData: [],
      // 表格分页配置
      pagination: {
        // 当前页码
        pageNum: 1,
        // 每页条数
        pageSize: 15,
        // 总条数
        rowsNumber: 0
      },
      cloneParams: {},
      tableData: []
    }
  },
  mounted () {
    this.getListInit()
  },
  methods: {
    getListInit () {
      this.$refs.workShopSearch.getWorkshops().then(() => {
        this.getList()
        this.getChartData()
      })
    },
    // 获取chart数据
    getChartData () {
      const { location } = this.params
      if (this.params.devices.length) {
        const params = {
          start: date.formatDate(this.params.dateRange[0], 'YYYY-MM-DD'),
          end: date.formatDate(this.params.dateRange[1], 'YYYY-MM-DD')
        }
        params.deviceTreeReqVO = {
          deviceIds: this.params.devices[0] !== 'all' ? this.params.devices : [],
          level: location.level || null,
          schemeId: location.id || null
        }
        getAlarmChartData(params).then(res => {
          this.chartData = res.data
        })
      } else {
        this.$message.warning('所选设备数量为0，请重新选择')
      }
    },
    // 获取数据
    getList () {
      const { location } = this.params
      if (this.params.devices.length) {
        let params = {
          start: date.formatDate(this.params.dateRange[0], 'YYYY-MM-DD'),
          end: date.formatDate(this.params.dateRange[1], 'YYYY-MM-DD'),
          sortValue: this.params.value,
          pageIndex: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        params.deviceTreeReqVO = {
          deviceIds: this.params.devices[0] !== 'all' ? this.params.devices : [],
          level: location.level || null,
          schemeId: location.id || null
        }
        this.cloneParams = _.cloneDeep(params)
        getAlarmList(params).then(res => {
          this.tableData = this.initInfo(res.data.list)
          this.pagination.rowsNumber = res.data.total
        })
      } else {
        this.$message.warning('所选设备数量为0，请重新选择')
      }
    },
    initInfo (info) {
      return info.map(item => {
        return {
          ...item,
          time: date.formatDate(item.time, 'YYYY-MM-DD HH:mm:ss')
        }
      })
    },
    // 重置
    resetSearch () {
      Object.assign(this.params, this.$options.data.call(this).params)
      this.$refs.workShopSearch.initData()
    },
    // 查询
    onSubmit () {
      this.pagination.pageNum = 1
      this.getList()
      this.getChartData()
    },
    // 导出Excel
    exportExcel () {
      let data = this.cloneParams
      data.excelHead = this.tableColumns.map(item => {
        return {
          field: item.field,
          name: item.label
        }
      })
      this.$q.loading.show()
      const params = [{ name: '' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      data['requestId'] = res.fileNameNew
      this.onSubscribe()
      downloadAlarm(data).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    getData (data) {
      return moment(data).format('YYYYMMDD')
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, `${this.getData(this.cloneParams.start)}-${this.getData(this.cloneParams.end)}机台报表_${this.statusList[4].label}明细统计.xls`)
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    // 表格排序
    sortable (type) {
      this.tableData = []
      if (this.params.sortBy === type) {
        if (this.params.value) {
          this.params.value = this.params.value === 'asc' ? 'desc' : 'asc'
        } else {
          this.params.value = 'asc'
        }
      } else {
        this.params.sortBy = type
        this.params.value = 'asc'
      }
      this.pagination.pageNum = 1
      this.getList()
    }
  }
}
</script>

<style lang="stylus">
</style>
